package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementQuery;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementServiceImpl implements IStatementService {

    @Autowired
    private StatementMapper statementMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private StatementItemMapper statementItemMapper;


    @Override
    public TablePageInfo<Statement> query(StatementQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<Statement>(statementMapper.selectForList(qo));
    }


    @Override
    public void save(Statement statement) {
        statement.setCreateTime(new Date());
        statementMapper.insert(statement);
    }

    @Override
    public Statement get(Long id) {
        return statementMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(Statement statement) {
        //获取数据，判断状态
        Statement statement1 = this.get(statement.getId());
        if (Statement.STATUS_PAID.equals(statement1.getStatus())) {
            throw new BusinessException("订单已支付，不可删除");
        }
        //将创建的时间，支付的相关时间去除掉，不用进行更新

        statementMapper.updateByPrimaryKey(statement);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            Statement statement = this.get(dictId);
            //当状态为已支付状态不能删除
            if (Statement.STATUS_PAID.equals(statement.getStatus())) {
                throw new BusinessException("已经支付的订单不能删除");
            }
            //删除结算单
            statementMapper.deleteByPrimaryKey(dictId);
            //删除中间表的数据
             statementMapper.deleteRelation(dictId);
            //若是预约的，把养修服务的状态改为已到店的状态
            if (statement.getAppointmentId()!=null) {
                //预约的订单的结算页删除
                appointmentMapper.changeCancelStatus(statement.getAppointmentId(),Appointment.STATUS_ARRIVAL);
            }

        }
    }

    @Override
    public List<Statement> list() {
        return statementMapper.selectAll();
    }

   @Override
    public boolean checkNameExsit(String name) {
        return statementMapper.selectByName(name) != null;
    }

    @Override
    public void saveItems(List<StatementItem> list) {
        //删除掉最后一个元素，获取折扣价格和statementId
        StatementItem item = list.remove(list.size() - 1);
        BigDecimal discountAmount = item.getItemPrice();
        Long statementId = item.getStatementId();
        //判空，为空不能结算
        if (list == null ||list.size() < 0) {
            throw new BusinessException("还未选择消费的服务项");
        }
        //清除中间表的数据，根据statementId
        statementItemMapper.deleteRelation(statementId);
        //遍历集合，计算出总金额和总数量，需要插入中间表数据
        BigDecimal totalAmount = new BigDecimal("0.00");
        BigDecimal totalCount = new BigDecimal("0.00");
        for (StatementItem statementItem : list) {
            totalAmount = totalAmount.add(statementItem.getItemPrice().multiply(statementItem.getItemQuantity()));
            totalCount = totalCount.add(statementItem.getItemQuantity());
            //将数据插入中间表中
            statementItemMapper.insert(statementItem);
        }
        //根据获取的数据更新结算单中的数据
        statementMapper.updateAmount(statementId,totalAmount,totalCount,discountAmount);
    }

    @Override
    public void pay(Long statementId) {
        //获取数据,获取结算单中的数据
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        //判断状态是否为消费中
        if (!statement.getStatus().equals(Statement.STATUS_CONSUME)) {
            throw new BusinessException("非法操作");
        }
        //修改状态,付款时间，收款人id，状态
        //ShiroUtils.getUser().getId()：获取当前登录系统的人，即收款人的id
        statementMapper.updateStatus(statementId,Statement.STATUS_PAID, ShiroUtils.getUser().getId());
    }

    @Override
    public Workbook export(Long statementId) {
        //创建一个
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("结算单详情");
        //查询数据
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        Row one = sheet.createRow(0);
        one.createCell(0).setCellValue("客户姓名");
        one.createCell(1).setCellValue("联系方式");
        one.createCell(2).setCellValue("车牌号码");
        one.createCell(3).setCellValue("汽车类型");
        one.createCell(4).setCellValue("服务类型");
        one.createCell(5).setCellValue("总消费金额");
        one.createCell(6).setCellValue("优惠金额");
        one.createCell(7).setCellValue("实付金额");
        one.createCell(8).setCellValue("服务项数量");
        one.createCell(9).setCellValue("付款时间");
        one.createCell(10).setCellValue("消费项目");
        Row row = sheet.createRow(1);
        row.createCell(0).setCellValue(statement.getCustomerName());
        row.createCell(1).setCellValue(statement.getCustomerPhone());
        row.createCell(2).setCellValue(statement.getLicensePlate());
        row.createCell(3).setCellValue(statement.getCarSeries());
        row.createCell(4).setCellValue(statement.getServiceType()==1?"保养":"维修");
        row.createCell(5).setCellValue(statement.getTotalAmount().doubleValue());
        row.createCell(6).setCellValue(statement.getDiscountAmount().doubleValue());
        row.createCell(7).setCellValue((statement.getTotalAmount().subtract(statement.getDiscountAmount())).doubleValue());
        row.createCell(8).setCellValue(statement.getTotalQuantity().doubleValue());
        row.createCell(9).setCellValue(DateFormatUtils.format(statement.getPayTime(),"yyyy-MM-dd HH:mm:ss"));
        List<StatementItem> statementItems = statementItemMapper.selectByStatementId(statementId);
        for (int i = 0; i < statementItems.size(); i++) {
            StatementItem item = statementItemMapper.selectByPrimaryKey(i + 1l);
            if (item!=null) {
                if (row.getCell(i+10)==null) {
                    row = sheet.createRow(i + 2);
                }
                row.createCell(10).setCellValue(item.getItemName());
            }
        }
        return workbook;
    }


}
